#include "SimpleDateFormat.h"

char* formatAnalyse(char* pos_input, char* DateTime, const char* item, const char* pendix)
{
	int tmp_length_before = 0;
	int tmp_length_after = 0;
	char* pos_after = NULL;

	pos_after = strstr(pos_input, item);

	if (pos_after != NULL)
	{
		tmp_length_before = strlen(pos_input);
		tmp_length_after = strlen(pos_after);
		
		if (tmp_length_before != tmp_length_after)
			strncat(DateTime, pos_input, tmp_length_before-tmp_length_after);
		
		strcat(DateTime, pendix);

		pos_input = pos_after + strlen(item);
	}

	return pos_input;
}

char* SimpleDateFormat(const char* format)
{
	char* pos_before = NULL;
	pos_before = (char *)format;
	char* DateTime = (char *)malloc(500);

	struct timeval tv;
	struct timezone tz;
	time_t lt = time(NULL);
	struct tm* ptr = localtime(&lt);
	char time_buf[50] = {0};
	char year[5] = {0};
	char month[3] = {0};
	char day[3] = {0};
	char hour[3] = {0};
	char minute[3] = {0};
	char sec[3] = {0};
	char msec[4] = {0};

	gettimeofday(&tv, &tz);
	
	sprintf(year, "%d", ptr->tm_year+1900);

	if ((ptr->tm_mon+1) > 10)
		sprintf(month, "%d", ptr->tm_mon+1);
	else 
		sprintf(month, "0%d", ptr->tm_mon+1);

	if (ptr->tm_mday > 10)
		sprintf(day, "%d", ptr->tm_mday);
	else 
		sprintf(day, "0%d", ptr->tm_mday);

	if (ptr->tm_hour > 10)
		sprintf(hour, "%d", ptr->tm_hour);
	else 
		sprintf(hour, "0%d", ptr->tm_hour);

	if (ptr->tm_min > 10)
		sprintf(minute, "%d", ptr->tm_min);
	else 
		sprintf(minute, "0%d", ptr->tm_min);

	if (ptr->tm_sec > 10)
		sprintf(sec, "%d", ptr->tm_sec);
	else 
		sprintf(sec, "0%d", ptr->tm_sec);

	if ((tv.tv_usec/1000) >= 100)
		sprintf(msec, "%d", tv.tv_usec/1000);
	else if ( ((tv.tv_usec/1000)>10) && ((tv.tv_usec/1000)<100) )
		sprintf(msec, "0%d", tv.tv_usec/1000);
	else
		sprintf(msec, "00%d", tv.tv_usec/1000);


	pos_before = formatAnalyse(pos_before, DateTime, "yyyy", year);
	pos_before = formatAnalyse(pos_before, DateTime, "MM", month);
	pos_before = formatAnalyse(pos_before, DateTime, "dd", day);
	pos_before = formatAnalyse(pos_before, DateTime, "hh", hour);
	pos_before = formatAnalyse(pos_before, DateTime, "mm", minute);
	pos_before = formatAnalyse(pos_before, DateTime, "ss", sec);
	pos_before = formatAnalyse(pos_before, DateTime, "ms", msec);

	return DateTime;
}
